package cn.incoder.moyun.core.web;

import cn.incoder.moyun.core.context.TenantContextHolder;
import cn.incoder.moyun.util.WebFrameworkUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//一次性过滤请求，获得租户id
public class TenantContextWebFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //使用 Spring 的 ContentCachingRequestWrapper 来缓存请求的 body，以便后续可以多次读取
        HttpServletRequest wrappedRequest = request;
        if (request.getContentType() != null && request.getContentType().contains("application/json")) {
            wrappedRequest = new ContentCachingRequestWrapper(request);
        }

        // 打印 tenant-id
        System.out.println("+++++tenant-id:" + wrappedRequest.getHeader("tenant-id") + "+++++");
        // 设置租户 ID
        Long tenantId = WebFrameworkUtils.getTenantId(wrappedRequest);
        if (tenantId != null) {
            TenantContextHolder.setTenantId(tenantId);
        }
        try {
            chain.doFilter(wrappedRequest, response);
        } finally {
            // 清理租户上下文
            TenantContextHolder.clear();
        }
    }
}
